const Roter=require('koa-router');
const {koaBody} = require('koa-body');
const fs = require("fs");
const path = require("path");
const { format } = require("date-fns"); // npm i date-fns
const { getteamDocByName,uploadteamdoc,getteamDocByID,getAllDocs,
        uploadInputteamdoc,getteamDocHistoryByteamdocID,delteamdocbytplid,
        delteamdocHis,getteamdocTplbyPath,updateShareOrState} =require('../controller/teamdoc.controller')
const {authToken } = require('../middleware/user.middleware')
const {teamdocUploadDir,teamdocTplUploadDir,} =require("../app/errorhandle")

const teamdocRouter = new Roter({
  prefix: '/teamdoc'
});

teamdocRouter.get('/',authToken,getAllDocs)

teamdocRouter.post('/getdocbyName',authToken,getteamDocByName)

teamdocRouter.post('/',getteamDocByID) 
teamdocRouter.post('/getdocTpl',authToken,getteamdocTplbyPath) 

teamdocRouter.post('/getdocHis',authToken,getteamDocHistoryByteamdocID)

teamdocRouter.post("/upload",authToken,
                    koaBody({
                      multipart: true, // 支持多文件上传
                      formLimit:"10mb",
                      jsonLimit:"10mb",
                      encoding: "gzip", // 编码格式
                      formidable: {
                        uploadDir: teamdocTplUploadDir, // 设置文件上传目录
                        keepExtensions: true, // 保持文件的后缀
                        maxFieldsSize: 10 * 1024 * 1024, // 文件上传大小限制
                        onFileBegin: (name, file) => {
                          const dir = teamdocTplUploadDir;
                          //console.log(process.cwd());//process.cwd()获取node的工作目录
                          //console.log(dir);
                          // 检查文件夹是否存在如果不存在则新建文件夹
                          if (!fs.existsSync(dir)) {
                              fs.mkdirSync(dir);
                            }
                          // 文件名称去掉特殊字符但保留原始文件名称
                          //console.log('filename:',file.name)
                          //console.log('filename:',file)
                          const fileName = file.originalFilename
                            .replaceAll(" ", "_")
                            .replace(/[`~!@#$%^&*()|\-=?;:'",<>\{\}\\\/]/gi, "_");
                          //file.originalFilename = fileName;
                          //file.newFilename=fileName
                          // 覆盖文件存放的完整路径(保留原始名称)
                          file.newFilename=fileName
                          file.filepath = `${dir}/${fileName}`
                          //console.log("file.path",file.path)
                        },
                        onError: (error) => {
                          app.body = { 
                            success:false, //response成功标识
                            code:200,
                            message:error.message,
                            data:error.message
                          };
                          return;
                        },
                      },
                    }),
                    uploadteamdoc)

teamdocRouter.post("/uploadInput",authToken,
                    koaBody({
                      multipart: true, // 支持多文件上传
                      formLimit:"10mb",
                      jsonLimit:"10mb",
                      encoding: "gzip", // 编码格式
                      formidable: {
                        uploadDir: teamdocUploadDir, // 设置文件上传目录
                        keepExtensions: true, // 保持文件的后缀
                        maxFieldsSize: 10 * 1024 * 1024, // 文件上传大小限制
                        onFileBegin: (name, file) => {
                          const dir = teamdocUploadDir;
                          if (!fs.existsSync(dir)) {
                              fs.mkdirSync(dir);
                            }
                          const fileName = file.originalFilename
                            .replaceAll(" ", "_")
                            .replace(/[`~!@#$%^&*()|\-=?;:'",<>\{\}\\\/]/gi, "_");
                          file.newFilename=fileName
                          file.filepath = `${dir}/${fileName}`
                        },
                        onError: (error) => {
                          app.body = { 
                            success:false, //response成功标识
                            code:200,
                            message:error.message,
                            data:error.message
                          };
                          return;
                        },
                      },
                    }),
                    uploadInputteamdoc)
                    
teamdocRouter.post('/del',authToken,delteamdocbytplid)      
teamdocRouter.post('/delHis',authToken,delteamdocHis)    

teamdocRouter.post('/updateShareState',authToken,updateShareOrState)  

module.exports = teamdocRouter;